<?php

require('config.php');
include('json.php');
include('logger.php');

$log = new logger(INFO, "logs/logs.txt");

// connect to database //
$link = mysql_connect($sql_host, $sql_user, $sql_pass);
mysql_select_db($sql_db);
mysql_query('SET NAMES \'utf8\'');


session_start();

/* Checks the database for new messages and events.
 *
 * @return JSON object of new messages/events if any, otherwise nothing
 * @author Joshua Gross
 * @update g henson
 **/
  function ping($away, $userid) {
	global $json, $log;
	
	  $log->log(DEBUG, "ping ".$userid);
	
      $user = checkInfo($userid,  array('is_online', 'last_ping'));
      if(!$user) {
         $set_status = mysql_query('UPDATE ' . SQL_PREFIX . 'moos_users SET is_online=0, last_ping=\'' . time() . '\' WHERE userid=' . $userid);
         return 'not_logged_in';
      }

      $set_status = mysql_query('UPDATE ' . SQL_PREFIX . 'moos_users SET is_online=\'' . mysql_real_escape_string($away + 1) . '\', last_ping=\'' . time() . '\' WHERE userid=' . $userid);
      
      $log->log(DEBUG, "ping : setstatus ok");
      
      /**
       * ???
       */
      //if($user['is_online'] != ($away + 1)) $this->userEvent($my->id, 'status', array('status'=>($away + 1)));
      
      $sql = 'SELECT msg.id, msg.message, msg.type, msg.sender, msg.recipient, us.username, ur.username as recipname '.
      		 'FROM ' . SQL_PREFIX . 'moos_messages msg, '. SQL_PREFIX . 'users us, users ur '.
      		 'WHERE msg.recipient=' . $userid . ' '.
      		 'AND msg.sender = us.id '.
      		 'AND msg.recipient = ur.id '.
      		 'GROUP BY sender, message, recipient ORDER BY id ASC';
      
      $log->log(DEBUG, $sql);

      $query = mysql_query($sql);
      
      $i=0; $j=0;
      $to_delete = array();
      $output = array();
      while ($row = mysql_fetch_assoc($query)) {
         if(strpos($row['type'], 'msg') !== false) {
            if($row['sender'] != $userid || $row['sender'] == $row['recipient']) {
               $output['messages'][$i++] = array('message'   => $row['message'],
                                                 'sender'    => $row['sender'],
               									 'sendername'=> $row['username'],
                                                 'recipient' => $row['recipname']);
               
               $to_delete[] = $row['id'];
            }
         } else if($row['type'] == 'event') {
            $output['events'][$j++] = array('event'     => $row['message'],
                                            'sender'    => $row['sender'],
            								'sendername'=> $row['username'],
                                            'recipient' => $row['recipname']);
                                            
            $event = explode(',', $row['message']);
            if($event[0] == 'status') $output['events'][$j-1]['group'] = $reverse_list[$row['sender']];
            
            $to_delete[] = $row['id'];
         } else if($row['type'] == 'server') {
            switch($row['message']) {
               case 'kick':
                  $this->logout();
                  print 'not_logged_in';
               break;
            }
            
            $to_delete[] = $row['id'];
         }
      }

      $log->log(DEBUG, "ping : to_delete=".count($to_delete));
      if(count($to_delete) > 0)
         $delete_new = mysql_query('DELETE FROM ' . SQL_PREFIX . 'moos_messages WHERE id IN(' . implode(',', $to_delete) . ')');         

      $log->log(DEBUG, "output = $output");
      return $json->encode($output);
   }
   
/**
    * Sends a message to another user.
    *
    * @return String 'sent' if successful, error string otherwise
    * @author Joshua Gross
    * @author modified by g henson
    **/
   function send($userid, $toid, $message, $font, $font_size, $font_color, $bold, $italic, $underline) {
      global $log;
      
      $log->log(DEBUG, "$userid send $message to $toid");
      if(!checkInfo($userid)) {
         $set_status = mysql_query('UPDATE ' . SQL_PREFIX . 'moos_users SET is_online=0, last_ping=\'' . time() . '\' WHERE userid=' . $userid);
         return 'not_logged_in';
      }
      
      $is_online = isOnline($toid);
      if($is_online > 0) {

         /* PROVISOIRE
         $check_blocked = mysql_query('SELECT id FROM ' . SQL_PREFIX . 'moos_blocklists WHERE user=\'' . strtolower($to) . '\' AND buddy=\'' . mysql_real_escape_string($this->username) . '\'');
         if(mysql_num_rows($check_blocked) > 0)
            return 'not_online';

         $check_blocked = mysql_query('SELECT id FROM ' . SQL_PREFIX . 'moos_blocklists WHERE buddy=\'' . strtolower($to) . '\' AND user=\'' . mysql_real_escape_string($this->username) . '\'');
         if(mysql_num_rows($check_blocked) > 0)
            return 'not_online';
		*/
         if(strlen(trim($message)) > 0 && strlen($message) <= 1500) {
            $message = ('<span style="font-family:' . mysql_real_escape_string($font) . ',sans-serif;font-size:' . mysql_real_escape_string($font_size > 24 ? 24 : $font_size) . 'px;color:' . mysql_real_escape_string($font_color) . ';">') .
                       ($bold == 'true' ? '<b>' : '') . ($italic == 'true' ? '<i>' : '') . ($underline == 'true' ? '<u>' : '') .
                       $message .
                       ($bold == 'true' ? '</b>' : '') . ($italic == 'true' ? '</i>' : '') . ($underline == 'true' ? '</u>' : '') .
                       ('</span>');
                       
            // protection des apostrophes
            $message = str_replace("'", "\'", $message);
            $to_insert = "('$message', 'msg', $userid , $toid, " . time() . ")";
            
            $query = mysql_query('INSERT INTO ' . SQL_PREFIX . 'moos_messages '.'
            					(message, type, sender, recipient, stamp) '.
            					'VALUES ' . 
            					$to_insert);
         } else {
            if(strlen($message) > 1500)
               return 'too_long';
         }
         
         return 'sent';
      } else {
         return 'not_online';
      }
   }
   
function sendevent($userid, $toid, $event) {
      global $log;
      $log->log(DEBUG, "send event $event from $userid to $toid");
      if(!checkInfo($userid)) {
         $set_status = mysql_query('UPDATE ' . SQL_PREFIX . 'moos_users SET is_online=0, last_ping=\'' . time() . '\' WHERE userid=' . $userid);
         return 'not_logged_in';
      }
      
      $is_online = isOnline($toid);
      if($is_online > 0) {

         /* PROVISOIRE
         $check_blocked = mysql_query('SELECT id FROM ' . SQL_PREFIX . 'moos_blocklists WHERE user=\'' . strtolower($to) . '\' AND buddy=\'' . mysql_real_escape_string($this->username) . '\'');
         if(mysql_num_rows($check_blocked) > 0)
            return 'not_online';

         $check_blocked = mysql_query('SELECT id FROM ' . SQL_PREFIX . 'moos_blocklists WHERE buddy=\'' . strtolower($to) . '\' AND user=\'' . mysql_real_escape_string($this->username) . '\'');
         if(mysql_num_rows($check_blocked) > 0)
            return 'not_online';
		*/
      	$log->log(INFO, "sendevent $userid to $toid : $event");
      	switch ($event) {
      		case 'close':
      			$message = "<span><b>Windows closed by recipient</b></span>";
      			$to_insert = "('$message', 'event', $userid , $toid, " . time() . ")";
            
            	$query = mysql_query('INSERT INTO ' . SQL_PREFIX . 'moos_messages '.'
            					(message, type, sender, recipient, stamp) '.
            					'VALUES ' . 
            					$to_insert);
      			break;
      		default :
      			// Do nothing
      			break;
      	}
        return 'sent';
      } else {
         return 'not_online';
      }
}

function store ($sender, $recipient, $conversation) {
	global $log, $store;
	if ($store) {
		$log->log(INFO, "store : sender = $sender, recipient = $recipient, conv = $conversation");
		
		$date = date ("dmY-His");
		$recipientname = getNameFromId($recipient);
		$filepath= STORE_DIR."/".$sender."_".$recipientname."_".$date.".html";
		$log->log(INFO, $filepath);
		$fp = fopen ($filepath, "w");
		fwrite($fp, $conversation);
		fclose($fp);
		
		$log->log(INFO, "conversation between $sender and $recipient stored in $filepath at ".$date);
	}
	return 'stored';
}
   
function checkLanguageFile ($lang) {
	global $log;
	$log->log(INFO, "checking language $lang");
	if (file_exists("languages/$lang")) {
		return 'lang_exists';
	}
	else {
		return 'not_exist';
	}
}
 /**
  * Check to see if the supplied user information is valid, and if so return specific information.
  *
  * @return false if information is invalid, array of data otherwise
  * @author Joshua Gross
 **/
   function checkInfo($userid, $return=array()) {
   	  global $log;
      if(count($return) > 0)
         $columns = implode(',', $return);
      else
         $columns = 'userid';
      
      $query = mysql_query('SELECT ' . $columns . ' FROM ' . SQL_PREFIX . 'moos_users WHERE userid=' . $userid . ' LIMIT 1');
		$log->log(INFO, 'SELECT ' . $columns . ' FROM ' . SQL_PREFIX . 'moos_users WHERE userid=' . $userid . ' LIMIT 1');
      if(mysql_num_rows($query) > 0) {
         return mysql_fetch_assoc($query);
      }
      else {
         return false;
      }
   }
   
   function isOnline ($userid) {
   		global $mode;
   		if ($mode == 'standalone') {
   			return isOnlineSimple($userid);
   		}
   		else {
   			return isOnlineJoomla($userid);
   		}
   }
	/**
    * Return a user's status.
    *
    * @return Integer representing user's status
    * @author Joshua Gross
    **/
   function isOnlineSimple($userid) {
      $query = mysql_query('SELECT is_online FROM ' . SQL_PREFIX . 'moos_users WHERE userid=' . $userid);
      
      $result = mysql_fetch_assoc($query);
      return $result['is_online'];
   }
   
   function isOnlineJoomla($userid) {
   		$sql = "SELECT COUNT(*) as is_online FROM ". SQL_PREFIX . "session WHERE userid =". (int) $user->id . " AND (guest = 0) AND (NOT ( usertype is NULL OR usertype = '' ))";
   		$query = mysql_query($sql);
      
      	$result = mysql_fetch_assoc($query);
      	return $result['is_online'];
   }
   
   /**
    * retrieves username for a given user id
    *
    * @param int $userid : id of the user
    * @return username
    */
   function getNameFromId($userid) {
      $query = mysql_query('SELECT username FROM ' . SQL_PREFIX . 'users WHERE id=' . $userid);
      
      $result = mysql_fetch_assoc($query);
      return $result['username'];
   }
   
   
  /*
   * MAIN*/
   $json = new JSON_obj();
       
   switch ($_POST['action']) {
   	case 'checklang':
   		print checkLanguageFile($_POST['lang']);
   		break;
   	case 'store':
   		print store ($_POST['caller'],$_POST['recipient'], $_POST['content']);
   		break;
   	case 'sendevent':
   		print sendevent ($_POST['caller'],$_POST['recipient'], $_POST['event']);
   		break;
   	case 'send': 
   		print send ($_POST['caller'],$_POST['recipient'], $_POST['message'], $_POST['font'], $_POST['fontsize'], 
   		            $_POST['fontcolor'], $_POST['bold'], $_POST['italic'], $_POST['underline']);
   		break;
   	case 'ping' :
   	default:
   		print ping ('false', $_POST['caller']);
   		break;
   }

mysql_close();
   
?>